package com.sqly.doc.menu.ycf;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.PopupMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.camera.CameraChoose;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.YcfCh42jkjc;
import com.sqly.doc.pojo.YcfChfs;
import com.sqly.doc.pojo.YcfDewccqsf;
import com.sqly.doc.pojo.YcfDyccqjc;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.sqly.doc.view.XListView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017-12-02.
 */

public class ycf_list extends MyBaseActivity {

    XListView listView;
    //标题
    TextView title, uname;
    LinearLayout back;
    ZLoadingDialog dialog;//加载动画
    Context con = ycf_list.this;
    private int pageNum1 = 1;// 无关键字页数
    List<YcfChfs> chfslist;//产后访视
    List<YcfDyccqjc> dyclist;//第一次产后访视
    List<YcfDewccqsf> ewcslist;//产后25访视
    List<YcfCh42jkjc> ch42list;//产后42访视
    int sfcs = 2;


    String type = "";//类型
    String url = "";//请求的路径
    private ImageView cx;
    private EditText key;
    @Override
    protected void initUI() {
        setContentView(R.layout.ycf_list);
        cx=(ImageView)findViewById(R.id.cx);
        cx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum1 = 1;
                getJumin();
            }
        });
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        type = getIntent().getStringExtra("type");
        if (type.equals("第1次产前检查服务"))
            url = HttpUrl.GetYcf1List;
        if (type.equals("第2次产前检查服务")) {
            url = HttpUrl.GetYcf25List;
            sfcs = 2;
        }
        if (type.equals("第3次产前检查服务")){
            url = HttpUrl.GetYcf25List;
            sfcs = 3;
        }
        if (type.equals("第4次产前检查服务")){
            url = HttpUrl.GetYcf25List;
            sfcs = 4;
        }
        if (type.equals("第5次产前检查服务")){
            url = HttpUrl.GetYcf25List;
            sfcs = 5;
        }
        if (type.equals("产后访视记录"))
            url = HttpUrl.GetChfsjlList;
        if (type.equals("产后42天健康检查记录"))
            url = HttpUrl.GetYcf42List;
        title.setText(type);
        key=(EditText)findViewById(R.id.key);
        uname.setText("新增");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("第1次产前检查服务"))
                    startActivity(new Intent(con, ycf_1.class).putExtra("type", "add"));
                if (type.equals("第2次产前检查服务"))
                    startActivity(new Intent(con, ycf_2.class).putExtra("type", "add"));
                if (type.equals("第3次产前检查服务"))
                    startActivity(new Intent(con, ycf_3.class).putExtra("type", "add"));
                if (type.equals("第4次产前检查服务"))
                    startActivity(new Intent(con, ycf_4.class).putExtra("type", "add"));
                if (type.equals("第5次产前检查服务"))
                    startActivity(new Intent(con, ycf_5.class).putExtra("type", "add"));
                if (type.equals("产后访视记录"))
                    startActivity(new Intent(con, ycf_chfsjl.class).putExtra("type", "add"));
                if (type.equals("产后42天健康检查记录"))
                    startActivity(new Intent(con, ycf_42.class).putExtra("type", "add"));

            }
        });
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //showPopupMenu(view, i);
                toEditView(i);
            }
        });
    }

    private void toEditView(final int position){
        Bundle b = new Bundle();
        if (type.equals("第1次产前检查服务")) {
            b.putSerializable("b", dyclist.get(position - 1));
            startActivity(new Intent(con, ycf_1.class).putExtras(b).putExtra("type", "edit"));
        } else if (type.equals("第2次产前检查服务")) {
            b.putSerializable("b", ewcslist.get(position - 1));
            startActivity(new Intent(con, ycf_2.class).putExtras(b).putExtra("type", "edit"));
        } else if (type.equals("第3次产前检查服务")) {
            b.putSerializable("b", ewcslist.get(position - 1));
            startActivity(new Intent(con, ycf_3.class).putExtras(b).putExtra("type", "edit"));
        } else if (type.equals("第4次产前检查服务")) {
            b.putSerializable("b", ewcslist.get(position - 1));
            startActivity(new Intent(con, ycf_4.class).putExtras(b).putExtra("type", "edit"));
        } else if (type.equals("第5次产前检查服务")) {
            b.putSerializable("b", ewcslist.get(position - 1));
            startActivity(new Intent(con, ycf_5.class).putExtras(b).putExtra("type", "edit"));
        } else if (type.equals("产后访视记录")) {
            b.putSerializable("b", chfslist.get(position - 1));
            startActivity(new Intent(con, ycf_chfsjl.class).putExtras(b).putExtra("type", "edit"));
        } else if (type.equals("产后42天健康检查记录")) {
            b.putSerializable("b", ch42list.get(position - 1));
            startActivity(new Intent(con, ycf_42.class).putExtras(b).putExtra("type", "edit"));
        }
    }

    private void toPaiZhaoView(final int position){
        Bundle b = new Bundle();
        if (type.equals("第1次产前检查服务")) {
            YcfDyccqjc itemInList = dyclist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfDyccqjc1")
            );
        } else if (type.equals("第2次产前检查服务")) {
            YcfDewccqsf itemInList = ewcslist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfDewccqsf2")
            );
        } else if (type.equals("第3次产前检查服务")) {
            YcfDewccqsf itemInList = ewcslist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfDewccqsf3")
            );
        } else if (type.equals("第4次产前检查服务")) {
            YcfDewccqsf itemInList = ewcslist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfDewccqsf4")
            );
        } else if (type.equals("第5次产前检查服务")) {
            YcfDewccqsf itemInList = ewcslist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfDewccqsf5")
            );
        } else if (type.equals("产后访视记录")) {
            YcfChfs itemInList = chfslist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfChfs")
            );
        } else if (type.equals("产后42天健康检查记录")) {
            YcfCh42jkjc itemInList = ch42list.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "YcfCh42jkjc")
            );
        }
    }
    PopupMenu popupMenu;
    @SuppressLint("RestrictedApi")
    private void showPopupMenu(View view, final int position ) {
        // View当前PopupMenu显示的相对View的位置
        popupMenu = new PopupMenu(ycf_list.this, view, Gravity.END);
        // menu布局
        popupMenu.getMenuInflater().inflate(R.menu.list_menu, popupMenu.getMenu());
        // menu的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Bundle b = new Bundle();
//                if(item.getItemId() == R.id.item_edit){
//                    toEditView(position);
//                }else if(item.getItemId() == R.id.item_pz){
//                    toPaiZhaoView(position);
//                }
                return false;
            }
        });

        // PopupMenu关闭事件
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                //Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
            }
        });
        //使用反射，强制显示菜单图标
        try {
            Field field = popupMenu.getClass().getDeclaredField("mPopup");
            field.setAccessible(true);
            MenuPopupHelper mHelper = (MenuPopupHelper) field.get(popupMenu);
            mHelper.setForceShowIcon(true);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        popupMenu.show();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetWorkUtils.isNetworkConnected(con)) {//联网状态
            getJumin();
        }
    }

    @Override
    protected void initListener() {

    }

    public void getJumin() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        ps.add("sfcs", sfcs+"");
        if(!StringUtils.isEmpty(key.getText().toString()))
            ps.add("XINGMING",key.getText().toString());
      /*  ps.add("XINGMING",SharedPreferencesUtils.getParam(con,"uname","").toString());*/
        UserClient.get(url, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {

                    if (type.equals("第1次产前检查服务")) {
                        List<YcfDyccqjc> ll = JSON.parseArray(
                                ret.getList(), YcfDyccqjc.class);
                        if (pageNum1 == 1) {
                            dyclist = new ArrayList<YcfDyccqjc>();
                        }
                        for (int i = 0; i < ll.size(); i++) {

                            dyclist.add(ll.get(i));
                        }
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<YcfDyccqjc>(con, dyclist, R.layout.ycf_chfsjl_item) {
                            @Override
                            public void convert(ViewHolder helper, YcfDyccqjc item) {
                                helper.setText(R.id.xm, item.getXINGMING());
                                helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                                helper.setText(R.id.sfrq,  DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setSelection(dyclist.size() - ll.size());
                    }
                    if (type.equals("第2次产前检查服务") || type.equals("第3次产前检查服务") || type.equals("第4次产前检查服务") || type.equals("第5次产前检查服务")) {
                        List<YcfDewccqsf> ll = JSON.parseArray(
                                ret.getList(), YcfDewccqsf.class);
                        if (pageNum1 == 1) {
                            ewcslist = new ArrayList<YcfDewccqsf>();
                        }
                        for (int i = 0; i < ll.size(); i++) {

                            ewcslist.add(ll.get(i));
                        }
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<YcfDewccqsf>(con, ewcslist, R.layout.ycf_chfsjl_item) {
                            @Override
                            public void convert(ViewHolder helper, YcfDewccqsf item) {
                                helper.setText(R.id.xm, item.getXINGMING());
                                helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                                helper.setText(R.id.sfrq,DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setSelection(ewcslist.size() - ll.size());
                    }
                    if (type.equals("产后访视记录")) {
                        List<YcfChfs> ll = JSON.parseArray(
                                ret.getList(), YcfChfs.class);
                        if (pageNum1 == 1) {
                            chfslist = new ArrayList<YcfChfs>();
                        }
                        for (int i = 0; i < ll.size(); i++) {

                            chfslist.add(ll.get(i));
                        }
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<YcfChfs>(con, chfslist, R.layout.ycf_chfsjl_item) {
                            @Override
                            public void convert(ViewHolder helper, YcfChfs item) {
                                helper.setText(R.id.xm, item.getXINGMING());
                                helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                                helper.setText(R.id.sfrq, DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setSelection(chfslist.size() - ll.size());
                    }
                    if (type.equals("产后42天健康检查记录")) {
                        List<YcfCh42jkjc> ll = JSON.parseArray(
                                ret.getList(), YcfCh42jkjc.class);
                        if (pageNum1 == 1) {
                            ch42list = new ArrayList<YcfCh42jkjc>();
                        }
                        for (int i = 0; i < ll.size(); i++) {

                            ch42list.add(ll.get(i));
                        }
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<YcfCh42jkjc>(con, ch42list, R.layout.ycf_chfsjl_item) {
                            @Override
                            public void convert(ViewHolder helper, YcfCh42jkjc item) {
                                helper.setText(R.id.xm, item.getXINGMING());
                                helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                                helper.setText(R.id.sfrq,  DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setSelection(ch42list.size() - ll.size());
                    }

                   /* /////////////////////////////////////////////////////////////////////////本地化
                    List<YcfChfs> dblist = DataSupport.where("CARDNUM=?",SharedPreferencesUtils.getParam(con,"cardnum","").toString()).find(YcfChfs.class);
                    if (dblist.size() > 0) {//
                        for (int i = 0; i < ll.size(); i++) {
                            List<YcfChfs> jlist = DataSupport.where("CARDNUM=?",SharedPreferencesUtils.getParam(con,"cardnum","").toString()).find(YcfChfs.class);
                            if (jlist.size() > 0) {
                                if (jlist.get(0).getIsupdate().equals("1")) {//本地数据没有更新，可以删除添加新的
                                    Log.i("产后访视数据", "删除后插入的数据");
                                    jlist.get(0).delete();
                                    ll.get(i).setIsupdate("1");//设置不需要更新的操作
                                    ll.get(i).save();
                                } else {//本地有数据保存还没有上传
                                    //不需要任何操作
                                }
                            } else {//本地数据没有
                                Log.i("产后访视数据", "直接插入的数据");
                                ll.get(i).setIsupdate("1");//设置不需要更新的操作
                                ll.get(i).save();
                            }

                        }
                    } else {
                        Log.i("产后访视数据", "直接插入的数据");
                        for (YcfChfs j : ll) {
                            j.setIsupdate("1");//设置不需要更新的操作
                            j.save();
                        }
                    }
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
                } else {
                    if(pageNum1==1)
                    listView.setAdapter(new CommonAdapter<YcfCh42jkjc>(con, new ArrayList<YcfCh42jkjc>(), R.layout.ycf_chfsjl_item) {
                        @Override
                        public void convert(ViewHolder helper, YcfCh42jkjc item) {
                            helper.setText(R.id.xm, item.getXINGMING());
                            helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                            helper.setText(R.id.sfrq,  DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                        }
                    });
                }
            }
        });
    }
}
